package org.ccay.security.web;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.ccay.core.util.StringUtil;
import org.ccay.security.entity.Permission;
import org.ccay.security.reaml.IPermissionMetadataScanner;

public class BindingURLAuthorizationFilter extends AuthorizationFilter{
	
	private Map<String,String> urlToPermissionMap;
	
	private IPermissionMetadataScanner scanner;
	
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		String requestURI = getPathWithinApplication(request);
		if(getUrlToPermissionMap().containsKey(requestURI)){
			Subject subject = getSubject(request, response);
			return subject.isPermitted(getUrlToPermissionMap().get(requestURI));
		}
		return true;
	}
	
	
	protected Map<String, String> getUrlToPermissionMap(){
		if(urlToPermissionMap == null){
			urlToPermissionMap = new HashMap<String,String>();
			Set<Permission> permissions = scanner.loadPermissionsMetadatas();
			for(Permission permission : permissions){
				if(!StringUtil.isNullOrEmpty(permission.getBindingURL())){
					String url = permission.getBindingURL();
					if(!url.startsWith("/")){
						url = "/"+permission.getBindingURL();
					}
					urlToPermissionMap.put(url, permission.getPermissionString());
				}
			}
		}
		return urlToPermissionMap;
	}

	
	public void setScanner(IPermissionMetadataScanner scanner) {
		this.scanner = scanner;
	}
}
